package com.wwwc.index.servlet;

import java.io.*;
import java.security.*;
import javax.servlet.http.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import com.wwwc.util.web.*;
import com.wwwc.index.ejb.EJBManager;
import com.wwwc.index.ejb.user.*;

public class UserRegisterServlet  extends HttpServlet {
    private User ejbdb;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    {
	try {
	    response.setContentType("text/html");
	    PrintWriter out     = response.getWriter();
	    HttpSession session = request.getSession(true);
	    String user_ip      = request.getRemoteAddr();
	    String call_path    = request.getContextPath()+request.getServletPath();

	    String action = request.getParameter("aid");

	    String activation_url = request.getParameter("activation_url");
	    if(activation_url == null) {
		System.out.println("UserRegisterServlet:Error:activation_url==null");
		return;
	    }

	    if(ejbdb == null) {
		ejbdb = (User)EJBManager.getEJB("java:comp/env/ejb/UserEJB", "User");
	    }

	    if(ejbdb.tableExists("USER_PROFILE_3WCENTER") == 0) { //Table not found
		System.out.println(ejbdb.createUserProfileTable());
	    }
	    else if(ejbdb.tableExists("USER_PROFILE_3WCENTER") == -1){ //Error
		out.println("<B>System Error. Please try again!</B>");
		return;
	    }

	    out.println(MyJavaScript.disableHistory());

	    //===================================================================
	    // registration
	    //===================================================================

	    if(action == null) { 
		String error = null;
		StringBuffer sbf = new StringBuffer ();
		String submit         = request.getParameter("UserRegisterServletSubmit");
		String pass1          = "";
		String pass2          = "";
		String user           = "";
		String email          = "";
		String fname          = "";
		String lname          = "";
		String photo          = "";
		String zip            = "";
		String country        = "";
		String month          = "";
		String day            = "";
		String year           = "";
		String gender         = "";
		String marital_status = "";
		String user_edu       = "";
		String img_key        = "";
		String industry       = "";
		String job_title      = "";
		String phone_area_code = "";
 
		// img_key set by PasswordImageServlet
		
		if(submit != null) {
		    try {
		
			String form_id = request.getParameter("submit_id");
			if(form_id == null || !form_id.equals(session.getAttribute("submit_id"))) {
			    return;
			}

			pass1    = request.getParameter("pass_word1");
			pass2    = request.getParameter("pass_word2");
			user     = request.getParameter("user_name");		
			email    = request.getParameter("user_email");
			zip      = request.getParameter("user_zip");
			country  = request.getParameter("country");
			month    = request.getParameter("op_age_month");
			day      = request.getParameter("op_age_day");
			year     = request.getParameter("op_age_year");
			gender   = request.getParameter("op_sex");
			user_edu = request.getParameter("op_edu");
			img_key  = request.getParameter("img_key");
		
			String format1 = "ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwxyz-'";
			String format2 =format1+"_0123456789.";

			MyUserInputCheck ck = new MyUserInputCheck();
			if(!ck.checkFormat("Username", user, format2)) {
			    error = ck.getMessage().toString();
			}

			if(error == null && !ck.checkSize("Username", user , 5, 20)) {
			    error = ck.getMessage().toString();;
			}

			if(ejbdb == null) {
			    ejbdb = (User)EJBManager.getEJB("java:comp/env/ejb/UserEJB", "User");
			}

			String query = null;
			String temp  = null;

			if(error == null) {
			    if(ejbdb.usernameExists(user)) {
				error = "Sorry. Username is not avaiable!";
			    }
			}

			if(error == null) {
			    if(ejbdb.emailHasBeenRegisted(email) && !email.equals("aaindex@yahoo.com")) {
				error = "Sorry. E-mail [ "+email+" ] has been registed by other user!";
			    }
			}
			
			if (error == null && !pass1.equals(pass2)) {
			    error = "Password and Re-typed password are not same!";
			}

			if(error == null && !ck.checkSize("Password", pass1, 5, 20)) {
			    error = ck.getMessage().toString();
			}

			if(error == null && !ck.checkEmail(email)) {
			    error = ck.getMessage().toString();
			}

			if(error == null && month.length()==0) {
			    error = "Please select your birth month!";
			}

			if(error == null && day.length()==0) {
			    error = "Please select your birth date!";
			}
			
			if(error == null && year.length()==0) {
			    error = "Please select your birth year!";
			}

			if(error == null && gender.length()==0) {
			    error = "Please select your gender!";
			}

			if(error == null && user_edu.startsWith("----")) {
			    error = "Please select your education level!";
			}
			if(error == null && !ck.checkZipCode(zip)) {
			    error = ck.getMessage().toString();
			}
			if(error == null && country.startsWith("----")) {
			    error = "Please select your country!";
			}
			if(error == null && !img_key.equals((String)session.getAttribute("img_key"))) {
			    error = "Please enter your image pin. Case sensitive!";
			}

			//========================================================================
			// save user info
			//========================================================================

			if(error == null) {
			    if(day.length()==1) {
				day = "0"+day;
			    }
			    if(month.length()==1) {
				month = "0"+month;
			    }

			    if(pass1.indexOf("'") != -1) {
				pass1 = pass1.replaceAll("'","''");
			    }

			    String activ_code = (""+System.currentTimeMillis()).substring(9);
			    int access_level = 1;

			    if(ejbdb.addNewUserProfile(user, pass1, access_level, email, fname, lname, photo, year+"-"+month+"-"+day, 
						       gender, user_edu, marital_status, industry, job_title, phone_area_code, zip, 
						       country, activ_code) != 1) {
				error = "Save data error. Please check your data!";
			    }

			    
			    if(error == null) {
				if(!sendVerifyEmail(email, user, year+"-"+month+"-"+day, activ_code, activation_url)) {
				    error = "Sendding e-mail error!";
				}
			    }
			    
			    if(error == null) {
				sbf.append("<CENTER>");
				sbf.append(activationMessage(email));
				sbf.append("<BR>");
				sbf.append(activationForm(call_path,  "0-30", "1"));
				sbf.append("</CENTER>");
				session.setAttribute("submit_id", null);
				out.println(sbf);
				return ;
			    }
			}
		    }
		    catch (IOException e) {
			error = "Save data error! Please try again.";
		    }
		}

		String submit_id = ""+System.currentTimeMillis();
	
		try {
		    session.setAttribute("submit_id", submit_id);

		    sbf.append("<CENTER>");
		    sbf.append("<FORM method='post' action='"+call_path+"'>");
		    sbf.append("<TABLE border='0' width='100%'>");
		    sbf.append("<TR><TD style='font-size: 12pt' align='center'>");
		    sbf.append("<B>All fields are required.</B></TD></TR>");
	
		    if(error != null && error.length()>0) { 
			sbf.append("<TR><TD style='font-size: 10 pt' align='center'>");
			sbf.append("<img src=/images/star.gif border=0><I>"+error+"</I>");
			sbf.append("</TD></TR>");
		    }

		    sbf.append("<TR><TD></TD></TR>");
		    sbf.append("</TABLE>");

		    sbf.append("<TABLE border='0' width='100%'  style='font-size: 10 pt'>");
		    sbf.append("<TR><TD align=right>3WCenter ID (User Name):</TD>");
		    sbf.append("<TD align='left'><input type='text' maxLength='20' name='user_name' value='"+user+"' size='20'></TD>");
		    sbf.append("</TR>");
		    sbf.append("<TR><TD align='right'>Password:</TD>");
		    sbf.append("<TD align='left'>");
		    sbf.append("<input type='password' name='pass_word1' value='"+pass1+"' maxLength='20' size='20'></TD>");
		    sbf.append("</TR>");
		    sbf.append("<TR>");

		    sbf.append("<TD align='right'>Re-type Password:</TD>");
		    sbf.append("<TD align='left'>");
		    sbf.append("<INPUT maxLength='20' name='pass_word2' value='"+pass2+"' type='password' size='20'>");
		    sbf.append("</TD>");
		    sbf.append("</TR>");

		    sbf.append("<TR>");
		    sbf.append("<TD align='right'>Current Email:</TD>");
		    sbf.append("<TD align='left'><INPUT maxLength='64' name='user_email' value='"+email+"' size='20'></TD>");
		    sbf.append("</TR>");

		    sbf.append("<TR>");
		    sbf.append("<TD colspan=2>&nbsp;</TD>");
		    sbf.append("</TR>");

		    sbf.append("<TR>");
		    sbf.append("<TD align='right'>Birthday:</TD>"); 
		    sbf.append("<TD>");
		    sbf.append("<SELECT name='op_age_month' style='font-size=8pt'>");
		    sbf.append("<OPTION value=''>Month</OPTION>");
		    sbf.append(MyHtml.getBirthMonthOption(month));
		    sbf.append("</SELECT>");
		    sbf.append("<SELECT name='op_age_day'  style='font-size=8pt'>");
		    sbf.append("<OPTION value=''>Day</OPTION>");
		    sbf.append(MyHtml.getBirthDayOption(day));
		    sbf.append("</SELECT>");
		    sbf.append("<SELECT name='op_age_year'  style='font-size=8pt'>");
		    sbf.append("<OPTION value=''>Year</OPTION>");
		    sbf.append(MyHtml.getBirthYearOption(year));
		    sbf.append("</SELECT>");
		    sbf.append("</TD>");
		    sbf.append("</TR>");

		    sbf.append("<TR>");
		    sbf.append("<TD align='right'>Gender:</TD>"); 
		    sbf.append("<TD><SELECT name='op_sex'  style='font-size=8pt'>");
		    sbf.append("<option value=''>---------</option>");
		    sbf.append(MyHtml.getGenderOption(gender));
		    sbf.append("</SELECT>");
		    sbf.append("</TD>");
		    sbf.append("</TR>");
		    
		    sbf.append("<TR>");
		    sbf.append("<TD align='right'>Education:</TD>"); 
		    sbf.append("<TD>");
		    sbf.append(MyHtml.getEducationOption("op_edu", user_edu));
		    sbf.append("</TD>");
		    sbf.append("</TR>");

		    sbf.append("<TR>");
		    sbf.append("<TD align='right'>Zip/postal code:</TD>"); 
		    sbf.append("<TD><input type='text' size='10' maxLength='10' name='user_zip' value='"+zip+"'>");
		    sbf.append("</TD>");
		    sbf.append("</TR>");

		    sbf.append("<TR>");
		    sbf.append("<TD align='right'>Country:</TD>"); 
		    sbf.append("<TD>"+MyHtml.getCountryOption("country",country));
		    sbf.append("</TD>");
		    sbf.append("</TR>");

		    sbf.append("<TR>");
		    sbf.append("<TD colspan=2>&nbsp;</TD>");
		    sbf.append("</TR>");

		    sbf.append("<TR>");
		    sbf.append("<TD align='right'>Please enter&nbsp;");
		    sbf.append("<IMG src='PasswordImage' width='80' height='25' border='1'></TD>");
		    sbf.append("<TD align='left'>");
		    sbf.append("<INPUT maxLength='20' name='img_key' value='' size='15' type='password'>");
		    sbf.append("&nbsp;<I>(*Case sensitive)</I></TD>");
		    sbf.append("</TR>");

		    sbf.append("</TABLE>");
		    sbf.append("<BR>");
		    sbf.append("<TABLE border='0' width='100%'>");
		    sbf.append("<TR>");
		    sbf.append("<TD align='center'>");
		    sbf.append("<input type='submit' value='Submit' name='UserRegisterServletSubmit' style='font-size: 8pt'>");
		    sbf.append("<input type='reset' value='Reset' name='B2' style='font-size: 8pt'>");
		    sbf.append("</TD>");
		    sbf.append("</TR>");
		    sbf.append("</TABLE>");
		    
		    sbf.append("<TABLE>");
		    sbf.append("<TR>");
		    sbf.append("<TD align='center'  style='font-size: 8pt' height='100'>");
		    sbf.append("<IFRAME SRC=/html/PrivacyPolicy.html WIDTH=700 HEIGHT=120></IFRAME>");
		    sbf.append("</TD>");
		    sbf.append("</TR>");
		    sbf.append("</TABLE>");
		    sbf.append("<input type='hidden' name='submit_id' value='"+submit_id+"'>");
		    sbf.append("</FORM>");
		    sbf.append("</CENTER>");
		}
		catch (Exception e) {
		    System.out.println("UserRegisterBean:Error:105"+e);
		}
		
		out.println(sbf);
	    }

	    //===================================================================
	    // activation (verification)
	    //===================================================================
	    
	    if(action != null && action.equals("1")) {
		if(ejbdb == null) {
		    ejbdb = (User)EJBManager.getEJB("java:comp/env/ejb/UserEJB", "User");
		}

		String uid = request.getParameter("uid");
		String vid = request.getParameter("vid");

		if(ejbdb.activeUserAccount(uid, vid) ==1) {
		    out.println(MyMessage.htmlMessage("<BR><BR>Your account has been actived. Please sign in.<BR>Thank You!"));		  
		} 
		else {
		    out.println("<BR>");
		    out.println("<TABLE align=center>");
		    out.println("<TR><TD align=center style='font-size: 12pt' heigth=200>");
		    out.println("Your activation code has been sent to you through e-mail.</TD></TR>");
		    out.println("<TR><TD align=center>");
		    out.println("<img src=/images/star.gif border=0><I>Activation error.</I>");
		    out.println("</TD></TR>");
		    out.println("<TR><TD align=center height=200>"+activationForm(call_path, "0-30", "1")+"</TD></TR>");
		    out.println("</TABLE>");
		}
	    }
	}
	catch (Exception e) {
	    System.out.println("UserRegisterServlet:Error:401:"+e);
	}
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
    {
	doPost(request, response);
    }

    private boolean sendVerifyEmail (String to, String username, String userage, 
				     String active_code, String activation_url) {
	String from     = "E-mail.Verification@3wcenter.com";
	String euser    = "Verification";
	String epass    = "LiNguyen5788";
	String subject  = "3WCenter E-mail Verification";        

	String content =
	    "Welcome!\n"+
	    "Please verify your account information:\n\n"+
	    "Username:\t"+username+"\n"+
	    "Account Activation Code : \t"+active_code+"\n\n"+
	    "Birthday:"+userage+" (Can not be changed.)\n"+
	    "You can modify your account information after you sign in.\n\n"+
	    "Please click this link to active your account\n"+
	   
	    activation_url+"&aid=1&uid="+username+"&vid="+active_code+"&sw="+System.currentTimeMillis()+
	    "\nIf you can not see the above link, please type:\n"+
	    activation_url+"&aid=1&uid="+username+"&vid="+active_code+"&sw="+System.currentTimeMillis()+
	    "\nin your browser address field to active your account.\nThank your!\n\n\n"+
	    "--3WCenter.com";


	try {
	    SendMail smail = new SendMail();
	    if(!smail.send(from, euser, epass, to, subject, content)) {
		return false;
	    }
	}
	catch (Exception e) {
	    return false;
	}     
	return true; 
    }

    private StringBuffer activationMessage(String email) {
	StringBuffer sbf = new StringBuffer ();
	sbf.append("<BR><B>Thank you!</B><BR>A activation code has been sent to:"+email+".");
	sbf.append("<BR>Please open your e-mail, <B>click</B> the link that ");
	sbf.append("3WCenter.com sent to you or <BR> type the activation code in this page to ");
	sbf.append("active your account.");
	sbf.append("<BR>");
	return sbf;
    }

    private StringBuffer activationForm(String call_path, String did, String aid) {
	StringBuffer sbf = new StringBuffer ();
	sbf.append("<FORM method=post action='"+call_path+"'>");
	sbf.append("<TABLE cellSpacing=0 cellPadding=1 border=1 style='font-size: 10pt'>");
	sbf.append("<TR><TD>User Name:</TD>");
	sbf.append("<TD><input type=text name=uid value='' size=20 maxLength=50></TD></TR>");
	sbf.append("<TR><TD>Activation code:</TD>");
	sbf.append("<TD><input type=password name=vid value='' size=20 maxLength=20></TD></TR>");
	sbf.append("<TR><TD colspan=2 align=center><input type=submit name=B value=Submit style='font-size: 8pt'></TD></TR>");
	sbf.append("</TABLE>");
	sbf.append("<input type='hidden' name='did' value='"+did+"'>");
	sbf.append("<input type='hidden' name='aid' value='"+aid+"'>");
	sbf.append("</FORM>");
	return sbf;
    }
}

